<template>
  <div class="panel-box">
    <el-container>
      <el-aside>
        <div class="top-bar">
          <!--          <el-button type="primary" @click="showImportDialog('stdy')">从数据库导入</el-button>-->
          总数：{{ stdyList.length }}
          <div class="right">
            <el-button type="primary" @click="addStdyDialogVisible=true">新增</el-button>
          </div>
        </div>
        <div class="inner-box">
          <el-input v-model="stdyFilterGjz" placeholder="实体名称/实体表名" suffix-icon="el-icon-search"></el-input>
          <div class="stdy-list-box" style="margin-top: 10px">
            <div v-for="item in stdyList"
                 v-show="item.stmc.indexOf(stdyFilterGjz)>-1||item.stbm.indexOf(stdyFilterGjz)>-1"
                 :key="item.stdybm" :class="{active:currStdy.stdybm===item.stdybm}"
                 class="list-item" @click="queryStjgListByStdy(item)">
              <div class="mc-box">
                <div>{{ item.stmc }}</div>
                <div style="font-size: 12px;color:red;">{{ item.stbm }}</div>
              </div>
              <div class="btn-box" @click.stop="{}">
                <div class="btn edit-btn" title="编辑" @click="editStdy(item)"></div>
                <div class="btn delete-btn" title="删除"
                     @click="preDel(delStdy,item,`即将删除【${item.stmc}】,删除后不可恢复，是否继续？`)"></div>
              </div>
            </div>
          </div>
        </div>
      </el-aside>
      <el-divider direction="vertical"></el-divider>
      <el-main class="noPadding">
        <div class="top-bar">
          <div>{{ `${currStdy.stmc}(${currStdy.stbm})` }}</div>
          <div class="right">

            <el-button type="primary" @click="stgxgl()">实体关系管理</el-button>
            <el-button type="primary" @click="showImportByFormDialog()">从表单数据导入</el-button>
            <el-button type="primary" @click="showImportByJsonDialog()">从JSON数据导入</el-button>
            <!--          <el-button type="primary" @click="showImportDialog('stjg')">从数据库导入</el-button>-->
            <el-button type="primary" @click="editStjg()">新增</el-button>
          </div>
        </div>
        <el-table
            :data="stjgList"
            height="calc(100% - 30px)"
            stripe
            style="width: 100%">
          <el-table-column
              label="序号"
              type="index"
              width="50">
          </el-table-column>
          <el-table-column
              label="字段描述"
              prop="zdms"
              show-overflow-tooltip>
          </el-table-column>
          <el-table-column
              label="字段名称"
              prop="zdmc">
          </el-table-column>
          <!--          <el-table-column-->
          <!--              label="字段类型">-->
          <!--            <template slot-scope="{row}">-->
          <!--              {{ zdlxObj[row.zdlx] || row.zdlx }}-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column
              label="数据源">
            <template slot-scope="{row}">
              {{ sjyObj[row.sjybm] || row.sjybm || '无' }}
            </template>
          </el-table-column>
          <el-table-column
              label=创建时间
              prop="cjsj"
              sortable
              width="180">
          </el-table-column>
          <el-table-column
              align="center"
              label="操作"
              width="118px">
            <template slot-scope="{row}">
              <el-link type="primary" @click="editStjg(row)">编辑</el-link>
              <el-link style="margin-left: 15px" type="danger"
                       @click="preDel(delStjg,row,`即将删除【${row.zdms}】,删除后不可恢复，是否继续？`)">删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>

    <xj-dialog :title="(stdyForm.stdybm?'编辑':'新增')+'实体'"
               :visible="addStdyDialogVisible">
      <el-form :model="stdyForm">
        <el-form-item label="实体表名" label-width="120px">
          <el-input v-model="stdyForm.stbm" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="实体名称" label-width="120px">
          <el-input v-model="stdyForm.stmc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAddStdyBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleAddStdyBtnClick(true)">确定</el-button>
      </div>
    </xj-dialog>

    <xj-dialog :title="(stjgForm.stjgbm?'编辑':'新增')+'实体结构'"
               :visible="addStjgDialogVisible">
      <el-form :model="stjgForm">
        <el-form-item label="字段名称" label-width="120px">
          <el-input v-model="stjgForm.zdmc" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="字段描述" label-width="120px">
          <el-input v-model="stjgForm.zdms" autocomplete="off"></el-input>
        </el-form-item>
        <!--        <el-form-item label="字段类型" label-width="120px">-->
        <!--          <el-select v-model="stjgForm.zdlx" style="width: 100%;">-->
        <!--            <el-option-->
        <!--                v-for="(mc,zdlx) in zdlxObj"-->
        <!--                :key="zdlx"-->
        <!--                :label="mc"-->
        <!--                :value="zdlx">-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="数据源" label-width="120px">
          <el-select v-model="stjgForm.sjybm" filterable style="width: 100%;">
            <el-option label="无" value=""/>
            <el-option
                v-for="(sjymc,sjybm) in sjyObj"
                :key="sjybm"
                :label="sjymc"
                :value="sjybm">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAddStjgBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleAddStjgBtnClick(true)">确定</el-button>
      </div>
    </xj-dialog>
    <!--<xj-dialog :visible="importDialogVisible"-->
    <!--           height="100%"-->
    <!--           title="从数据库导入实体" width="1200px">-->

    <!--  <el-container>-->
    <!--    <el-aside width="400px">-->
    <!--      <el-form :model="importForm" label-width="100px">-->

    <!--        <el-form-item label="数据库类型">-->
    <!--          <el-select v-model="importForm.className" placeholder="请选择" style="width: 99%;">-->
    <!--            <el-option v-for="(k,v) in classNameList" :key="k" :label="k" :value="v"></el-option>-->
    <!--          </el-select>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="连接字符串">-->
    <!--          <el-input v-model="importForm.url"></el-input>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="用户名">-->
    <!--          <el-input v-model="importForm.username"></el-input>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="密码">-->
    <!--          <el-input v-model="importForm.password" show-password type="password"></el-input>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="查询语句">-->
    <!--          <el-input v-model="importForm.sql" rows="11" type="textarea"></el-input>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="">-->
    <!--          <el-button type="primary" @click="executeSql">查询</el-button>-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->
    <!--    </el-aside>-->
    <!--    <el-divider direction="vertical"></el-divider>-->
    <!--    <el-main>-->
    <!--      <el-form label-width="100px">-->
    <!--        <div class="column-box">-->
    <!--          <el-form-item label="导入类型">-->
    <!--            <el-radio-group v-model="importForm.type" disabled>-->
    <!--              <el-radio-button label="stdy">实体定义</el-radio-button>-->
    <!--              <el-radio-button label="stjg">实体属性</el-radio-button>-->
    <!--            </el-radio-group>-->
    <!--          </el-form-item>-->
    <!--          <el-form-item label="实体定义">-->
    <!--            <el-select v-model="importForm.stdybm" disabled-->
    <!--                       placeholder="请选择" style="width: 99%;">-->
    <!--              <el-option v-for="column in stdyList" :key="column.stdybm" :label="column.stmc"-->
    <!--                         :value="column.stdybm"></el-option>-->
    <!--            </el-select>-->
    <!--          </el-form-item>-->
    <!--          <el-form-item label="名称列">-->
    <!--            <el-select v-model="importForm.bmColumn" placeholder="请选择" style="width: 99%;">-->
    <!--              <el-option v-for="column in importForm.columns" :key="column" :label="column"-->
    <!--                         :value="column"></el-option>-->
    <!--            </el-select>-->
    <!--          </el-form-item>-->
    <!--          <el-form-item label="描述列">-->
    <!--            <el-select v-model="importForm.mcColumn" placeholder="请选择" style="width: 99%;">-->
    <!--              <el-option v-for="column in importForm.columns" :key="column" :label="column"-->
    <!--                         :value="column"></el-option>-->
    <!--            </el-select>-->
    <!--          </el-form-item>-->
    <!--        </div>-->
    <!--      </el-form>-->
    <!--      <el-table-->
    <!--          :data="importForm.result"-->
    <!--          height="calc(100% - 95px)"-->
    <!--          style="width: 100%">-->
    <!--        <el-table-column type="index"></el-table-column>-->
    <!--        <el-table-column-->
    <!--            :prop="importForm.bmColumn"-->
    <!--            label="名称">-->
    <!--        </el-table-column>-->
    <!--        <el-table-column-->
    <!--            :prop="importForm.mcColumn"-->
    <!--            label="描述">-->
    <!--        </el-table-column>-->
    <!--        <el-table-column-->
    <!--            label="操作"-->
    <!--            width="100px">-->
    <!--          <template slot-scope="{row}">-->
    <!--            <el-link :disabled="isAdd(row)" type="primary" @click="addSt(row)">添加</el-link>-->
    <!--          </template>-->
    <!--        </el-table-column>-->
    <!--      </el-table>-->
    <!--    </el-main>-->
    <!--  </el-container>-->

    <!--  <div slot="footer" class="dialog-footer">-->
    <!--    <el-button @click="handleImportBtnClick(false)">取消</el-button>-->
    <!--    <el-button type="primary" @click="handleImportBtnClick(true)">确定</el-button>-->
    <!--  </div>-->
    <!--</xj-dialog>-->

    <xj-dialog :visible="importByJsonDialogVisible"
               height="100%"
               title="从JSON导入属性"
               width="960px">
      <el-container>
        <el-aside width="400px">
          <vue-json-editor
              v-model="inputJson"
              lang="zh"
              mode="code"
              style="height: 100%" @json-change="jsonChange" @has-error="hasError"/>
        </el-aside>
        <el-divider direction="vertical"></el-divider>
        <el-main>
          <div>
            <el-select v-model="selectKey">
              <el-option
                  v-for="(v,k) in outputJson"
                  :key="k"
                  :label="k"
                  :value="k">
              </el-option>
            </el-select>
            <el-button style="margin-left: 10px;" type="primary" @click="createStdy">创建实体</el-button>
          </div>
          <el-table
              ref="tableByJson"
              :data="outputJson[selectKey]"
              :select-on-indeterminate="false"
              height="calc(100% - 28px)"
              row-key="zdmc"
              style="width: 100%">
            <el-table-column
                :selectable="(row)=>!isJsonAdd(row)"
                type="selection"
                width="100">
            </el-table-column>
            <el-table-column
                label="字段名称"
                prop="zdmc">
            </el-table-column>
            <el-table-column
                label="字段描述"
                prop="zdms">
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleImportByJsonBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleImportByJsonBtnClick(true,'Json')">导入</el-button>
      </div>
    </xj-dialog>
    <xj-dialog :visible="importByFormDialogVisible"
               height="100%"
               title="从表单导入属性"
               width="960px">
      <el-container>
        <el-main>
          <div style="display: flex;align-items: center;margin-bottom: 10px">
            <div style="width: 80px;">表单数据</div>
            <el-input v-model="inputForm" placeholder="请输入表单数据">
              <template slot="append">
                <el-button type="primary" @click="parseForm(inputForm)">解析</el-button>
              </template>
            </el-input>
          </div>
          <div>
            <el-select v-model="selectKey">
              <el-option
                  v-for="(v,k) in outputForm"
                  :key="k"
                  :label="k"
                  :value="k">
              </el-option>
            </el-select>
            <el-button style="margin-left: 10px;" type="primary" @click="createStdy">创建实体</el-button>
          </div>
          <el-table
              ref="tableByForm"
              :data="outputForm[selectKey]"
              :select-on-indeterminate="false"
              height="calc(100% - 66px)"
              row-key="zdmc"
              style="width: 100%">
            <el-table-column
                :selectable="(row)=>!isJsonAdd(row)"
                type="selection"
                width="100">
            </el-table-column>
            <el-table-column
                label="字段名称"
                prop="zdmc">
            </el-table-column>
            <el-table-column
                label="字段描述"
                prop="zdms">
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleImportByJsonBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleImportByJsonBtnClick(true,'Form')">导入</el-button>
      </div>
    </xj-dialog>
    <xj-dialog :visible="stgxglDialogVisible"
               height="100%"
               show-close
               title="实体关系管理" @close="stgxglDialogVisible=false">
      <el-tree :data="stgxList"
               node-key="gxbm">
        <template v-slot="{ data }">
          <div class="tree-node">
            <div class="label-box">
              <div v-html="data.zzdLabel"/>
              <div class="eq">=</div>
              <div v-html="data.czdLabel"/>
            </div>
            <div class="btn-box">
              <div class="btn" title="增加节点" @click="addStgx({fgxbm:data.fgxbm})">+</div>
              <div class="btn" title="增加下级节点" @click="addStgx({fgxbm:data.gxbm})">+</div>
            </div>
          </div>
        </template>
      </el-tree>

    </xj-dialog>

    <xj-dialog :title="(stgxForm.xmbm?'编辑':'新增')+'实体关系'"
               :visible="addStgxDialogVisible">
      <el-form :model="stgxForm">
        <el-form-item label="主字段名称" label-width="120px">
          <el-cascader
              v-model="stgxForm.zzdmcArr"
              :options="stTree"
              filterable
              separator="."></el-cascader>
        </el-form-item>
        <el-form-item label="从字段名称" label-width="120px">
          <el-cascader
              v-model="stgxForm.czdmcArr"
              :options="stTree"
              filterable
              separator="."></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleAddStgxBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleAddStgxBtnClick(true)">确定</el-button>
      </div>
    </xj-dialog>
  </div>
</template>

<script>
import XjDialog from "@/components/XjDialog";
import commonMixins from "@/mixins/commonMixins";
import vueJsonEditor from "vue-json-editor";
import MyTree from "@/components/MyTree";
import { mapState } from "vuex";
import pako from 'pako'

export default {
  components: { XjDialog, vueJsonEditor, MyTree },
  name: "Stgl",
  mixins: [commonMixins],
  data () {
    return {
      classNameList: {
        "dm.jdbc.driver.DmDriver": '达梦',
        "com.mysql.cj.jdbc.Driver": 'MySQL',
      },
      // importForm: {
      //   url: '',
      //   className: 'dm.jdbc.driver.DmDriver',
      //   username: '',
      //   password: '',
      //   sql: "",
      //   result: [],
      //
      //   columns: [],
      //   type: 'stdy',
      //   stdybm: '',
      //   bmColumn: 'stbm',
      //   mcColumn: 'stmc',
      // },
      stdyList: [],
      importByJsonDialogVisible: false,
      // importDialogVisible: false,
      addStdyDialogVisible: false,
      addStjgDialogVisible: false,
      stdyForm: {
        stdybm: '',
        stbm: '',
        stmc: '',
      },
      stjgForm: {
        stjgbm: '',
        zdmc: '',
        zdms: '',
        zdlx: '',
        sjybm: '',
      },
      currStdy: { stdybm: '', stbm: '', stmc: '' },
      sjyObj: {},
      stjgList: [],
      zdlxObj: {
        input: '输入框',
        date: '日期',
        time: '时间',
        radio: '单选',
        checkbox: '多选',
        selectTree: '下拉树',
      },
      inputJson: [],
      outputJson: {},
      selectKey: '',
      stdyFilterGjz: '',

      stgxList: [],
      addStgxDialogVisible: false,
      stgxglDialogVisible: false,
      stgxForm: {
        xmbm: '',
        zzdmcArr: [],
        czdmcArr: [],
      },
      // showTable: false
      outputForm: {},
      inputForm: "",
      importByFormDialogVisible: false
    }
  },
  // watch: {
  //   selectKey() {
  //     this.showTable = false
  //     setTimeout(() => {
  //       this.showTable = true
  //     }, 100)
  //   }
  // },
  computed: {
    ...mapState(['stTree', 'stTreeObj']),
  },
  async mounted () {
    await this.$store.dispatch("loadMxstgxList")
    let sjyList = await this.$api.queryCanUseSjy({ rybm: this.yhxx.rybm })
    sjyList.forEach(item => {
      this.$set(this.sjyObj, item.sjybm, item.sjymc)
    })
    this.queryStdyListByXmbm()
  },
  methods: {
    stgxgl () {
      this.queryStgxListByXmbm()
      this.stgxglDialogVisible = true
    },
    async queryStgxListByXmbm () {
      let stgxList = await this.$api.queryStgxListByXmbm({ xmbm: this.xmItem.xmbm })
      stgxList.forEach(item => {
        item.zzdLabel = this.getZwmc(item.zzdmc)
        item.czdLabel = this.getZwmc(item.czdmc)
      })
      this.stgxList = this.$listToTree(stgxList, "gxbm", "fgxbm")
    },
    getZwmc (key) {
      let item = this.stTreeObj[key]
      return item ? `${item.zdzwmc}<br><span style="color:red;">${key}</span>` : `<span style="color:red;">${key}</span>`
    },
    addStgx (stgx) {
      stgx = {
        zzdmc: "",
        czdmc: "",
        gxbm: '',
        fgxbm: '',
        ...stgx
      }
      this.stgxForm = {
        ...stgx,
        zzdmcArr: stgx.zzdmc.split("."),
        czdmcArr: stgx.czdmc.split(".")
      }
      this.addStgxDialogVisible = true
    },
    async handleAddStgxBtnClick (isConfirm) {
      if (isConfirm) {
        try {
          let zzdmc = this.stgxForm.zzdmcArr.join(".")
          if (!zzdmc) throw new Error("请选择主字段名称")
          let czdmc = this.stgxForm.czdmcArr.join(".")
          if (!czdmc) throw new Error("请选择从字段名称")
          if (this.stgxForm.gxbm) {

            this.$message({ message: "修改成功", type: "success" })
          } else {
            await this.$api.addStgx({
              xmbm: this.xmItem.xmbm,
              fgxbm: this.stgxForm.fgxbm || "-1",
              zzdmc,
              czdmc
            })
            this.$message({ message: "添加成功", type: "success" })
          }
          this.queryStgxListByXmbm()
        } catch (e) {
          return this.$message({ message: e.message, type: "error" })
        }

      }
      this.addStgxDialogVisible = false
    },


    async handleImportByJsonBtnClick (isConfirm, l) {
      if (isConfirm) {
        let table = this.$refs[`tableBy${l}`]
        let selection = table.selection
        try {
          let allRes = await Promise.all(selection.map(item => this.addStjg({
            ...item,
            zdlx: 'input'
          }, false)))
          this.queryStjgList()
          this.$message({ message: "导入成功", type: "success" })
        } catch (e) {
          return this.$message({ message: "导入失败，" + e.message, type: "error" })
        }
      }
      this.importByJsonDialogVisible = false
      this.importByFormDialogVisible = false
      this.inputJson = []
      this.inputForm = ''
      this.outputJson = {}
      this.outputForm = {}
      this.selectKey = ''
    },
    parseTq (cqjgj, pk = "", resJson = {}) {
      for (let cqjgjKey in cqjgj) {
        if (!cqjgj.hasOwnProperty(cqjgjKey)) continue
        let cqjgjValue = cqjgj[cqjgjKey]
        if (!cqjgjValue.length) continue
        let newKey = (pk && (pk + "_")) + cqjgjKey
        for (const cqjgjValueElement of cqjgjValue) {
          if (cqjgjValueElement.akxbm) {
            // 是案卡项
            if (!resJson[newKey]) resJson[newKey] = []
            if (resJson[newKey].every(item => item.zdmc !== cqjgjValueElement.akxbm)) {
              // let isAdd = this.stjgList.some(_ => _.zdmc === cqjgjValueElement.akxbm)
              resJson[newKey].push({
                zdmc: cqjgjValueElement.akxbm,
                zdms: cqjgjValueElement.akxmc,
                // isAdd
              })
            }
          } else {
            let re = this.parseTq(cqjgjValueElement, newKey, resJson)
            resJson = {
              ...resJson,
              ...re
            }
          }
        }

      }
      return resJson
    },
    parseAk (akItem, pk = "", resJson = {}) {
      let newKey = akItem.stbm
      for (const zdsjElement of akItem.zdsj) {
        if (!resJson[newKey]) resJson[newKey] = []
        if (resJson[newKey].every(item => item.zdmc !== zdsjElement.zdmc)) {
          // let isAdd = this.stjgList.some(_ => _.zdmc === zdsjElement.zdmc)
          resJson[newKey].push({
            zdmc: zdsjElement.zdmc,
            zdms: zdsjElement.zdzwmc || zdsjElement.zdmc,
            // isAdd
          })
        }
      }
      if (akItem.cbsj) {
        for (const cbsjElement of akItem.cbsj) {
          let re = this.parseAk(cbsjElement, newKey, resJson)
          resJson = {
            ...resJson,
            ...re
          }
        }
      }
      return resJson
    },
    parse (jsonStr = []) {
      if (!Array.isArray(jsonStr)) {
        return this.$message({ message: "json数据固定为数组", type: "error" })
      }
      let resJson = {}
      for (const jsonStrElement of jsonStr) {
        let re = {}
        if (jsonStrElement.cqjgj) {
          re = this.parseTq(jsonStrElement.cqjgj, jsonStrElement.wbmbbh, resJson)
        } else if (jsonStrElement.stbm) {
          re = this.parseAk(jsonStrElement, "", resJson)
        } else {
          this.$message({ message: "暂不支持该格式的json数据", type: "warning" })
        }
        resJson = {
          ...resJson,
          ...re
        }
      }
      this.selectKey = ""
      for (let resJsonKey in resJson) {
        this.selectKey = resJsonKey;
        break
      }
      this.outputJson = resJson
    },
    hasError (e) {
      this.parse([])
    },
    jsonChange (json) {
      this.parse(json)
    },
    showImportByJsonDialog () {
      // this.inputJson = []
      this.outputJson = {}
      this.selectKey = ''
      this.parse(this.inputJson)
      this.importByJsonDialogVisible = true
    },
    showImportByFormDialog () {
      this.outputForm = {}
      this.selectKey = ''
      // this.parseForm(this.inputForm)
      this.importByFormDialogVisible = true
    },
    parseForm (str) {
      if (!str) {
        return this.$message.error("表单数据不能为空")
      }
      let data
      try {
        data = pako.inflate(Buffer.from(str, "base64"), { to: "string" })
        data = JSON.parse(data)
      } catch (e) {
        return this.$message.error("表单解析异常，请检查数据")
      }

      let tables = {}

      function p (_data) {
        let list = _data.list
        if (list) {
          for (const listElement of list) {
            let columns = listElement.columns
            if (columns) {
              for (const column of columns) {
                p(column)
              }
            } else {
              let stbm = listElement.stbm
              let zdmc = listElement.stzd
              let zdms = listElement.name
              if (stbm) {
                if (!tables[stbm]) tables[stbm] = []
                if (!tables[stbm].find(item => item.zdmc === zdmc)) {
                  tables[stbm].push({
                    zdmc,
                    zdms
                  })
                }
              }
            }
          }
        }
      }

      p(data)

      // console.log(JSON.parse(JSON.stringify(tables)))
      this.outputForm = tables;
      for (let tablesKey in tables) {
        this.selectKey = tablesKey
        break
      }

    },
    // showImportDialog (type) {
    //   this.importForm.type = type
    //   this.importForm.stdybm = this.currStdy.stdybm
    //   let importForm = myLocalStorage.getItem("importForm", {})
    //   let p = importForm[type]
    //   if (p) {
    //     this.importForm.url = p.url
    //     this.importForm.className = p.className
    //     this.importForm.username = p.username
    //     this.importForm.password = p.password
    //     this.importForm.sql = p.sql
    //   }
    //
    //   this.importDialogVisible = true
    // },
    async addSt (obj) {
      try {
        if (!this.importForm.bmColumn || !this.importForm.mcColumn) {
          throw new Error("请选择【名称列】和【描述列】")
        }
        if (this.importForm.type === 'stdy') {
          let stbm = obj[this.importForm.bmColumn]
          let stmc = obj[this.importForm.mcColumn]
          await this.addStdy({ stbm, stmc })
        } else if (this.importForm.type === 'stjg') {
          let zdmc = obj[this.importForm.bmColumn]
          let zdms = obj[this.importForm.mcColumn]
          await this.addStjg({ zdmc, zdms, zdlx: 'input' })
        }
        this.$message({ message: "添加成功", type: 'success' })
      } catch (e) {
        this.$message({ message: e.message, type: 'error' })
      }
    },
    isJsonAdd (row) {
      return !!this.stjgList.find(item => item.zdmc === row.zdmc)
    },
    // isAdd (obj) {
    //   if (this.importForm.type === 'stdy') {
    //     if (!this.importForm.bmColumn || !this.importForm.mcColumn) return true
    //     let stbm = obj[this.importForm.bmColumn]
    //     if (!stbm) return true
    //     return !!this.stdyList.find(item => item.stbm === stbm)
    //   } else if (this.importForm.type === 'stjg') {
    //     if (!this.importForm.bmColumn || !this.importForm.mcColumn) return true
    //     let zdmc = obj[this.importForm.bmColumn]
    //     if (!zdmc) return true
    //     return !!this.stjgList.find(item => item.zdmc === zdmc)
    //   }
    //   return true
    // },
    async queryStdyListByXmbm () {
      this.stdyList = await this.$api.queryStdyListByXmbm({ xmbm: this.xmItem.xmbm })
      if (!this.stdyList.length) {
        this.currStdy = { stdybm: '', stbm: '', stmc: '' };
        this.stjgList = []
        return
      }
      let stdyItem = mySessionStorage.getItem('stdy-item', {})
      let stdy = this.stdyList.find(item => item.stdybm === stdyItem.stdybm)
      if (stdy == null) stdy = this.stdyList[0]
      this.queryStjgListByStdy(stdy)
    },
    // async executeSql () {
    //   let columns = []
    //   let result = []
    //   let importForm = myLocalStorage.getItem("importForm", {})
    //   let p = {
    //     url: this.importForm.url,
    //     className: this.importForm.className,
    //     username: this.importForm.username,
    //     password: this.importForm.password,
    //     sql: this.importForm.sql,
    //   }
    //   importForm[this.importForm.type] = p
    //   myLocalStorage.setItem("importForm", importForm)
    //   try {
    //     result = await this.$api.queryData(p)
    //     if (result.length) {
    //       for (let column in result[0]) {
    //         columns.push(column)
    //       }
    //     }
    //   } catch (e) {
    //     this.$message({ message: e.message, type: 'error' })
    //   }
    //   this.importForm.result = result
    //   this.importForm.columns = columns
    // },
    // async handleImportBtnClick (isConfirm) {
    //   if (isConfirm) {
    //
    //   }
    //   this.importDialogVisible = false
    // },
    async addStjg (stjg, refresh = true) {
      let res;
      if (stjg.stjgbm) {
        res = await this.$api.updateStjg({
          stjgbm: stjg.stjgbm,
          zdmc: stjg.zdmc,
          zdms: stjg.zdms,
          zdlx: stjg.zdlx,
          sjybm: stjg.sjybm
        })
      } else {
        res = await this.$api.addStjg({
          zdmc: stjg.zdmc,
          zdms: stjg.zdms,
          zdlx: stjg.zdlx,
          sjybm: stjg.sjybm,
          stdybm: this.currStdy.stdybm
        })
      }
      if (refresh) this.queryStjgList()
      return res
    },
    async handleAddStjgBtnClick (isConfirm) {
      if (isConfirm) {
        // 进行保存
        try {
          if (this.stjgForm.stjgbm) {
            await this.$api.updateStjg({
              stjgbm: this.stjgForm.stjgbm,
              zdmc: this.stjgForm.zdmc,
              zdms: this.stjgForm.zdms,
              zdlx: this.stjgForm.zdlx,
              sjybm: this.stjgForm.sjybm
            })
          } else {
            await this.$api.addStjg({
              zdmc: this.stjgForm.zdmc,
              zdms: this.stjgForm.zdms,
              zdlx: this.stjgForm.zdlx,
              sjybm: this.stjgForm.sjybm,
              stdybm: this.currStdy.stdybm
            })
          }
          this.queryStjgList()
        } catch (e) {
          this.$message({ message: e.message, type: 'error' })
          return
        }
      }
      this.addStjgDialogVisible = false
      this.stjgForm = { stjgbm: '', zdmc: '', zdms: '', zdlx: '', sjybm: '', }
    },
    async createStdy () {
      try {
        let it = this.stdyList.find(item => item.stbm === this.selectKey)
        if (it) throw new Error("实体表已存在，请勿重复添加")
        let stdybm = await this.addStdy({
          stmc: this.selectKey,
          stbm: this.selectKey
        }, false)
        mySessionStorage.setItem("stdybm", stdybm)
        this.queryStdyListByXmbm()
      } catch (e) {
        this.$message.error(`创建实体失败:${e.message}`)
      }
    },
    async addStdy (stdy, refresh = true) {
      let stdybm = stdy.stdybm
      if (stdybm) {
        await this.$api.updateStdy({
          stdybm: stdy.stdybm,
          stmc: stdy.stmc,
          stbm: stdy.stbm,
        })
      } else {
        stdybm = await this.$api.addStdy({
          stmc: stdy.stmc,
          stbm: stdy.stbm,
          xmbm: this.xmItem.xmbm
        })
      }
      if (refresh) {
        this.queryStdyListByXmbm()
      }
      return stdybm
    },
    async handleAddStdyBtnClick (isConfirm) {
      if (isConfirm) {
        // 进行保存
        try {
          await this.addStdy(this.stdyForm)
        } catch (e) {
          this.$message({ message: e.message, type: 'error' })
          return
        }
      }
      this.addStdyDialogVisible = false
      this.stdyForm = { stdybm: '', stbm: '', stmc: '' }
    },
    async delStdy (stdy) {
      try {
        await this.$api.deleteStdy({
          stdybm: stdy.stdybm
        })
        this.queryStdyListByXmbm()
        this.handleAddStdyBtnClick(false)
      } catch (e) {
        this.$message({ message: e.message, type: 'error' })
      }
    },
    async queryStjgListByStdy (stdy) {
      this.currStdy = stdy
      mySessionStorage.setItem("stdy-item", this.currStdy)
      this.queryStjgList()
    },
    editStdy (stdy) {
      this.stdyForm = { stdybm: stdy.stdybm, stbm: stdy.stbm, stmc: stdy.stmc }
      this.addStdyDialogVisible = true
    },
    async queryStjgList () {
      this.stjgList = await this.$api.queryStjgListByStbm({ stdybm: this.currStdy.stdybm })
    },
    async editStjg (stjg) {
      if (!this.currStdy.stdybm) return this.$message.error("请先选择实体")
      if (!stjg) {
        stjg = {
          stjgbm: "",
          zdmc: "",
          zdms: "",
          zdlx: "input",
          sjybm: "",
        }
      }
      this.stjgForm = {
        stjgbm: stjg.stjgbm,
        zdmc: stjg.zdmc,
        zdms: stjg.zdms,
        zdlx: stjg.zdlx,
        sjybm: stjg.sjybm,
      }
      this.addStjgDialogVisible = true
    },
    async delStjg (stjg) {
      await this.$api.deleteStjg({ stjgbm: stjg.stjgbm })
      this.queryStjgList()
    },
    async setGzdyQyzt (gzdy) {
      const pam = { gzbm: gzdy.gzbm, sfqy: 'Y' }
      if (gzdy.sfqy === 'Y') {
        pam.sfqy = "N"
      }
      await this.$api.setGzdyQyzt(pam)
      this.queryStjgList()
    }
  },
  beforeDestroy () {
    this.$store.dispatch('loadStTree')
  }
}
</script>

<style lang="scss" scoped>
.column-box {
  display: grid;
  grid-template-columns:repeat(2, 1fr);
  text-align: center;
}

::v-deep .jsoneditor-vue {
  height: 100%;
}

::v-deep .el-tree-node__content {
  height: unset;
}

.tree-node {
  display: flex;
  flex: 1;
  padding: 10px 0;

  .label-box {
    flex: 1;
    display: flex;
    align-items: center;

    .eq {
      margin: 0 10px;
    }
  }

  .btn-box {
    display: flex;
    align-items: center;

    .btn {
      width: 20px;
      text-align: center;

      &:hover {
        background-color: #ccc;
      }
    }
  }
}
</style>
